//
//  SYPlayerEditViewController.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2020/5/4.
//  Copyright © 2020 SanYi. All rights reserved.
//

#import "SYPlayerEditViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LFVideoEditingController.h"
#import "AVAsset+LFMECommon.h"
#import "UIViewController+GF.h"

@interface SYPlayerEditViewController ()<LFVideoEditingControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *stateLab; //加载lood

@property (copy, nonatomic) NSString *urlStr;

@property (copy, nonatomic) NSString *filePath;//视频路径

@property (weak, nonatomic) IBOutlet UIView *bgPlayerView;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, weak) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) UIImage *firstImage;
/** 需要保存到编辑数据 */
@property (nonatomic, strong) LFVideoEdit *videoEdit;
@property (nonatomic, strong) LFVideoEditingController *lfVideoEditVC;


@end

@implementation SYPlayerEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    self.stateLab = @""
//    self.taskId = @"glnp86suur7q4u0i0rqb";
    
    [self requestPlayerUrlStr];
    
//    self.urlStr = @"http://1257034971.vod2.myqcloud.com/c77b91a9vodcq1257034971/12ddd7d65285890797354366181/f0.mp4";
////
//    self.urlStr =  [self.urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//
//    [self writeToCacheWithUrl:self.urlStr];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}
#pragma mark - 请求视频地址
- (void)requestPlayerUrlStr {
    __weak typeof(self) weakSelf = self;
    
    if (self.taskId.length <= 0) {
        
        [MBProgressHUD mj_showError:@"视频转码中，请稍后重试！"];
        return;
    }
    [SYRequestAPI bb_TutorVideoUrlByTaskId:self.taskId success:^(NSString * _Nonnull pathUrl) {

        [weakSelf writeToCacheWithUrl:pathUrl];
        
    } fail:^(NSError *error) {
        
        [NSObject executeRunloop:^{
            
            [MBProgressHUD mj_showError:@"视频转码中，请稍后重试！"];
        } afterDelay:1.5];
//        [NSObject executeRunloop:^{
//            [self dismissViewControllerAnimated:YES completion:nil];
//        } afterDelay:1];
    }];
}


#pragma mark 写入缓存
- (void)writeToCacheWithUrl:(NSString *)urlStr
{
    _bgPlayerView.hidden = YES;
    _stateLab.hidden = NO;
    _stateLab.text = @"正在加载";
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
//        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
        //创建文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //获取document路径
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
        //写入路径
        NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
        
//        [data writeToFile:path atomically:YES];
        [self requestdataDownLoadFile:path urlstr:urlStr path:^(BOOL ispath, float progress) {
            if (ispath == YES) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 更新界面
                    [weakSelf fileTranscode:path];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 更新界面
                    weakSelf.stateLab.text = [NSString stringWithFormat:@"正在加载 %.2f%%",progress];
                });
                
            }
            
        }];
        
        
    });
}

- (void)fileTranscode:(NSString *)path {
    _bgPlayerView.hidden = NO;
    self.url  = [NSURL fileURLWithPath:path];//[NSURL URLWithString:self.urlStr];//
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.url options:nil];
    self.firstImage = [asset lf_firstImage:nil];
    _player = [AVPlayer playerWithURL:self.url];
//    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    playerLayer.frame = self.bgPlayerView.bounds;
    [self.bgPlayerView.layer addSublayer:playerLayer];
    _playerLayer = playerLayer;
    
    [self.player play];
}

- (void)requestdataDownLoadFile:(NSString *)filePath urlstr:(NSString *)urlStr path:(void(^)(BOOL ispath,float progress))path {
    
//    __weak typeof(self) weakSelf = self;
    [SYDownloadFile downloadFileWithUrl:urlStr success:^(id responseObject) {
        [MBProgressHUD mj_hideHUD];
        if (path) {
            path(YES,0);
        }
        
    } failure:^(NSError *error) {
//        [MBProgressHUD mj_hideHUD];
        [MBProgressHUD zr_showError:@"加载失败"];
        self.stateLab.text = @"加载失败";
        [NSObject executeRunloop:^{
            self.stateLab.hidden = YES;
        } afterDelay:1];
        
    } progress:^(float progress, long long bytesRead) {
        // [MBProgressHUD mj_hideHUDForView:self.view];
        
        if (path) {
            path(NO,progress);
        }
    } savePath:filePath];
    
    
}
//返回
- (IBAction)fanhuiBtnClick:(UIButton *)sender {
//    [self removeFromParentViewController];

    [self.navigationController popViewControllerAnimated:YES];
//    [self setNewOrientation:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
//    [NSObject executeRunloop:^{
//        [self dismissViewControllerAnimated:YES completion:nil];
//    } afterDelay:1];
//    
//    [self dismissViewControllerAnimated:YES completion:^{
//
//    }];
    
    
}
//编辑视频
- (IBAction)editingBtnClick:(UIButton *)sender {
        _lfVideoEditVC = [[LFVideoEditingController alloc] init];
        _lfVideoEditVC.delegate = self;
        _lfVideoEditVC.operationType = LFVideoEditOperationType_draw | LFVideoEditOperationType_clip;
        _lfVideoEditVC.defaultOperationType = LFVideoEditOperationType_clip; // 默认剪辑
        _lfVideoEditVC.operationAttrs = @{
            LFVideoEditDrawColorAttributeName:@(LFVideoEditOperationSubTypeDrawVioletRedColor), // 绘画紫罗兰红色
            LFVideoEditDrawBrushAttributeName:@(LFVideoEditOperationSubTypeDrawHighlightBrush), // 绘画笔刷
            //                                     LFVideoEditStickerAttributeName:@"描述（贴图路径）",
            LFVideoEditTextColorAttributeName:@(LFVideoEditOperationSubTypeTextAzureColor), // 字体天蓝色
            LFVideoEditFilterAttributeName:@(LFVideoEditOperationSubTypeProcessFilter), //滤镜效果
    //        LFVideoEditAudioMuteAttributeName:@(true), //关闭原音
            //                                     LFVideoEditAudioUrlsAttributeName:@"描述（音频路径）",
            LFVideoEditRateAttributeName:@(0.5), //播放速率
            LFVideoEditClipMinDurationAttributeName:@(1), //剪辑最小时间
            LFVideoEditClipMaxDurationAttributeName:@(600), // 剪辑最大时间
    //        LFVideoEditAudioUrlsAttributeName:@[[[NSBundle mainBundle] URLForResource:@"Voice.mp3" withExtension:nil]] // 额外音频
        };
        if (self.videoEdit) {
            _lfVideoEditVC.videoEdit = self.videoEdit;
        } else {
            [_lfVideoEditVC setVideoURL:self.url placeholderImage:self.firstImage];
        }
        [self.navigationController setNavigationBarHidden:YES];
        [self.navigationController pushViewController:_lfVideoEditVC animated:NO];
//    [self presentViewController:lfVideoEditVC animated:YES completion:^{
//
//    }];
}

#pragma mark - LFVideoEditingControllerDelegate
- (void)lf_VideoEditingControllerDidCancel:(LFVideoEditingController *)videoEditingVC
{
    [self.navigationController popViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES];
    [self.player seekToTime:kCMTimeZero];
    [self.player play];
}
- (void)lf_VideoEditingController:(LFVideoEditingController *)videoEditingVC didFinishPhotoEdit:(LFVideoEdit *)videoEdit
{
    [self.navigationController popViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:YES];
//    [self.player removeObserver:self forKeyPath:@"status"];
    if (videoEdit && videoEdit.editFinalURL) {
        self.player = [AVPlayer playerWithURL:videoEdit.editFinalURL];
        //得到视频连接，然后上传到服务器。
        [self updataImageRequestWithImage:videoEdit.editFinalURL];
        
    } else {
        self.player = [AVPlayer playerWithURL:self.url];
    }
//    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    _playerLayer.player = self.player;
    self.videoEdit = videoEdit;
    
    
}
//上传视频
-(void)updataImageRequestWithImage:(NSURL *)videoPath{
    
            NSMutableArray *dataImageArr = [NSMutableArray array];
            
            [dataImageArr addObject:videoPath];
            
                NSString *fileNames = @"";
                
                for (NSInteger i = 0; i<dataImageArr.count; i++) { {
                    if (i == 0) {
                        fileNames = @"ios/weike/weike_userHeader_0.MP4";
                    } else {
                        fileNames = [NSString stringWithFormat:@"%@,AddWorks_userHeader_%ld.MP4",fileNames,i];
                    }
                }
            }
//                
                NSDictionary *dict = @{@"fileNames":fileNames};
                [MBProgressHUD mj_showMessage:@"正在上传" toView:self.view];
                [SYRequestAPI uploadWithUrl:@"http://image.31waiyu.com/HttpUpload/HttpFileUpload.ashx" parameters:dict images:dataImageArr name:@"1" fileName:@"weike" progress:@"1" success:^(id responseObject) {
                    [MBProgressHUD hideHUDForView:self.view animated:NO];
                    NSArray *arr = responseObject[@"data"];
                    NSDictionary *pathDic= arr[0];
                    if (self.backVideoPath) {
                        self.backVideoPath(pathDic);
                    }
                    [self.navigationController popViewControllerAnimated:YES];

                } fail:^(NSError *error) {
    //                [MBProgressHUD mj_hideHUD];
                    [MBProgressHUD hideHUDForView:self.view animated:NO];

                    [MBProgressHUD zr_showError:error.domain];
                }];
    
//    [SYRequestAPI creatingUserHeaderUpdateFile:@[videoPath] fileType:@"2" fileBusinessType:@"video" fileName:fileNames success:^(id responseObject) {
//        
//    } fail:^(NSError *error) {
//        
//    }];
}




@end
